package mobilesearch.thread;

import android.content.ContentResolver;
import mobilesearch.data.ContactsData;
import mobilesearch.ui.BroadcastCommand;

import java.util.ArrayList;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import android.content.Intent;
import android.content.Context;

public class ContactsSearchThread extends Thread {

	private static final String TAG = "ContactsSearchThread";
	private ContentResolver resolver;
	private Context context;

	private String contactsId;
	private String displayDame;
	private String phoneNumber;

	public ContactsSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		Log.i(TAG, "run");
		super.run();
		ArrayList<ContactsData> contactsList = new ArrayList<ContactsData>();
		
		try{
			Cursor cursor = this.resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			if(cursor.moveToFirst()){
				Log.i(TAG, "cursor.moveToFirst()");
				do{
					ContactsData data = new ContactsData();
					
					int columnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
					this.contactsId = cursor.getString(columnIndex);
					data.setContactId(this.contactsId);
					
					int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
					this.displayDame = cursor.getString(displayNameIndex);
					data.setDisplayName(this.displayDame);
					
					//phone number cursor
					Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+this.contactsId, null, null);
					if(phoneCursor.moveToFirst()){
						int numberIndex = phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
						this.phoneNumber = phoneCursor.getString(numberIndex);
						data.setPhoneNumber(this.phoneNumber);
					}
					
					//add the contacts data to the array list
					contactsList.add(data);
					
				}while(cursor.moveToNext());
			}
		}catch(Exception exception){
			Log.i(TAG, exception.toString());
		}
	
		//broadcast the data to the activity
		if(!contactsList.isEmpty()){
			Intent contactsIntent = new Intent(BroadcastCommand.SEARCH_CONTACTS);
			contactsIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_CONTACTS, contactsList);
			this.context.sendBroadcast(contactsIntent);	
		}
	}
}
